package yu.zhou.njupt.fileprocessor;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import yu.zhou.njupt.fileprocessor.bean.CaseSensitive;
import yu.zhou.njupt.fileprocessor.bean.MatchMode;

/**
 * @author yu.zhou
 * 
 */
@SuppressWarnings("unused")
public class FileRename extends FileProcessor{
    
    private static final Logger logger = LoggerFactory.getLogger(FileRename.class);

    public FileRename() {
    	numOFThread = 1;
    }
    
    public FileRename(int threadNum) {
    	this.numOFThread = threadNum;
    }
    
	public int work(File sourcePath, File bakPath, Map<String, String> filenameMap, MatchMode matchMode, CaseSensitive caseSensitive) throws Exception {
		if (!sourcePath.exists()) {
			throw new Exception("源文件的根目录不存在,请检查!!!");
		} else if (!sourcePath.isDirectory()) {
			throw new Exception("提供的根目录是一个文件,请检查!!!");
		} else {
			numOfProcessFiles = 0;
			if (!bakPath.exists()) {
			    bakPath.mkdir();
			}
			
			renameMatchFiles(sourcePath, bakPath, filenameMap, matchMode, caseSensitive);

			return numOfProcessFiles;
		}
	}
	
	public int work(String sourcePathStr, String destinationPathStr, Map<String, String> filenameMap, MatchMode matchMode, CaseSensitive caseSensitive) throws Exception {
	    return work(new File(sourcePathStr), new File(destinationPathStr), filenameMap, matchMode, caseSensitive);
	}
	
	private void renameMatchFiles(File sourcePath, File bakPath, Map<String, String> filenameMap, MatchMode mode, CaseSensitive caseSensitive) throws IOException {
	    String sourcePathStr = sourcePath.getAbsolutePath() + File.separator;
	    
		for (File file : sourcePath.listFiles()) {
			if (file.isDirectory()) {
			    renameMatchFiles(file, bakPath, filenameMap, mode, caseSensitive);
			} else {
				String filename = file.getName();

				for (Entry<String,String> entry : filenameMap.entrySet()) {
					if (match(filename, entry.getKey(), mode, caseSensitive)) {
	                       FileUtils.copyFileToDirectory(file, bakPath);
					    file.renameTo(new File(sourcePathStr + entry.getValue()));
						numOfProcessFiles++;
					}
				}
			}
		}
	}
	
}
    
